package com.itic.appbase.applications.sys.role.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.role.persistence.model.Role;
import com.itic.appbase.applications.sys.role.persistence.model.RoleExample;
import com.itic.appbase.applications.sys.role.persistence.model.RoleExample.Criteria;
import com.itic.appbase.applications.sys.role.service.RoleService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

/**
 * 角色管理
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: shijun
 * @date: 2015年5月13日 上午9:21:44
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/sys/role")
public class RoleController
        extends BaseController {
    @Autowired
    private RoleService roleService;
    // 返回属性黑名单
    private static String[] ignoreProperties = new String[] { "createUser" };

    /**
     * 主页面
     * 
     * @return
     */
    @RequestMapping(value = "/init")
    public String initMain() {
        return "sys/role/roleMain";
    }

    /**
     * 新增页面
     * 
     * @return
     */
    @RequestMapping(value = "/initAdd")
    public String initAdd() {
        return "sys/role/roleAdd";
    }

    /**
     * 编辑页面
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initEdit")
    public String initEdit(String id, Model model){
        Role role = roleService.get(id);
        model.addAttribute(role == null ? new Role() : role);
        return "sys/role/roleEdit";
    }

    /**
     * 角色授权页面
     * 
     * @param id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initAuthorize")
    public String initAuthorize(String id, Model model) {
        Role role = roleService.get(id);
        model.addAttribute(role == null ? new Role() : role);
        return "sys/role/roleAuthorize";
    }

    /**
     * 数据列表展示
     * 
     * @param role
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(Role role, HttpServletRequest request) {
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 参数处理
        RoleExample roleExample = new RoleExample();
        // 封装分页参数
        roleExample = this.handlePageQuery(request, roleExample);
        // 封装查询条件
        roleExample = this.queryCondition(role, roleExample);
        // 获取数据
        List<Role> roleList = roleService.list(roleExample);
        // 返回属性处理
        List<Map<String, Object>> resultList = ValueHelper.tranList2MapList(roleList, ignoreProperties);
        // 获取数据总数
        int totalNum = roleService.count(roleExample);
        // 数据返回处理
        resultMap.put(IticConst.DATA, resultList);
        resultMap.put(IticConst.TOTAL_RECORDS, totalNum); // 总记录
        resultMap.put(IticConst.DISPLAY_RECORDS, totalNum);//
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return resultMap;
    }

    /**
     * 添加角色并同步更新角色资源表
     * 
     * @param role
     * @param resourceIds
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Map<String, Object> add(Role role, String resourceIds) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (null != role && StringHelper.isNotBlank(role.getName())) {
            result = roleService.addRole(role, resourceIds);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();// 参数不合法
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 角色修改
     * 
     * @param role
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(Role role) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != role && StringHelper.isNotBlank(role.getName())) {
            result = roleService.edit(role);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 删除角色
     * 
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids)  {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (StringHelper.isNotBlank(ids)) {
            List<String> idList = Arrays.asList(ids.trim().split(","));// 角色id
            RoleExample roleExample = new RoleExample();
            roleExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIdIn(idList);
            Role role = new Role();
            role.setUpdateTime(new Date());
            role.setIsEffective(DBConst.FALSE);
            result = roleService.deleteRole(role, roleExample, idList);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 获取角色信息
     * 
     * @param role
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getRoleTree")
    @ResponseBody
    public Map<String, Object> getRoleTree(Role role) {
        Map<String, Object> dataResult = new HashMap<String, Object>();
        RoleExample roleExample = new RoleExample();
        // 封装查询条件
        roleExample.setOrderByClause("create_Time asc");
        // 封装查询条件
        Criteria criteria = roleExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != role && StringHelper.isNotBlank(role.getId())) {
            criteria.andIdNotEqualTo(role.getId());// 过滤掉角色自身
        }
        // 查询数据
        List<Role> roleList = roleService.list(roleExample);
        dataResult.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        dataResult.put(IticConst.DATA, roleList);
        return dataResult;
    }

    /**
     * 校验角色名称是否重复
     * 
     * @param role
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/checkRoleExist")
    @ResponseBody
    public Map<String, Object> checkRoleExist(Role roleVo) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (null != roleVo) {
            RoleExample roleExample = new RoleExample();
            // 封装查询条件
            Criteria criteria = roleExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
            if (StringHelper.isNotBlank(roleVo.getName())) {// 角色名称
                criteria.andNameEqualTo(roleVo.getName());
            }
            if (StringHelper.isNotBlank(roleVo.getId())) {// 过滤掉自身
                criteria.andIdNotEqualTo(roleVo.getId());
            }
            // 获取数据
            List<Role> roleList = roleService.list(roleExample);
            if (null != roleList && !roleList.isEmpty()) {
                resultMap.put(IticConst.RESULT, ResponseCode.EXIST.getCode());// 角色名称已存在
            } else {
                resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());// 角色名称可用
            }
        } else {
            resultMap.put(IticConst.RESULT, ResponseCode.PARAM_INVALID.getCode());// 参数不合法
        }
        return resultMap;
    }

    /**
     * 封装查询条件
     * 
     * @param role
     *            查询条件
     * @param roleExample
     */
    private RoleExample queryCondition(Role role, RoleExample roleExample) {
        roleExample.setOrderByClause("create_Time asc");
        // 封装查询条件
        Criteria criteria = roleExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != role && StringHelper.isNotBlank(role.getName())) {// 角色名称
            criteria.andNameLike("%" + role.getName() + "%");
        }
        return roleExample;
    }
}